package com.test.rpc.test3;

import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;

import java.io.File;
import java.util.Map;

public class MyBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar, ResourceLoaderAware {

    ResourceLoader resourceLoader;
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        try {
            //获取@MyMapperScan包路径，并扫描
            Map<String, Object> attributes = importingClassMetadata.getAnnotationAttributes(MyMapperScan.class.getName());
            System.out.println(attributes);
            for (String s : attributes.keySet()) {
                System.out.println(s);
                System.out.println(attributes.get(s));
            }
            AnnotationAttributes annotationAttributes = AnnotationAttributes.fromMap(attributes);
            String packageName = annotationAttributes.getString("value");
            String packageFileName=packageName.replace(".","/");
            File[] files = resourceLoader.getResource(packageFileName).getFile().listFiles();
            for (File file : files) {
                System.out.println(file);
                String fileName = file.getName().replace(".class", "");
                Class<?> aClass = Class.forName(packageName+"."+fileName);
                if(aClass.isInterface()&&!aClass.isAnnotation()){
                    BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition();
                    GenericBeanDefinition beanDefinition = (GenericBeanDefinition) builder.getBeanDefinition();
                    beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(packageName+"."+fileName);
                    beanDefinition.setBeanClass(MyFactoryBean.class);
                    registry.registerBeanDefinition(fileName,beanDefinition);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }
}